package com.itheima.company.controller;

import com.itheima.common.controller.BaseController;
import com.itheima.common.entity.Result;
import com.itheima.common.entity.ResultCode;
import com.itheima.company.pojo.Department;
import com.itheima.company.service.DepartmentService;
import com.itheima.common.utils.IdWorker;;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * @author IntelliJ IDEA
 * @date 2020/10/22  9:26
 */
@RestController
@CrossOrigin
@RequestMapping("/company")
public class DepartmentController extends BaseController {

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private IdWorker idWorker;



    /**
     * 查询department全部列表
     */
    @GetMapping("/department")
    public Result findAllDepartmentByCompanyId(){
        System.out.println("companyId = " + this.companyId);
        return new Result(ResultCode.SUCCESS,departmentService.findAllDepartmentByCompanyId(this.companyId,this.companyName));
    }

    /**
     * 根据id查询department
     */
    @GetMapping("/department/{id}")
    public Result findDepartmentById(@PathVariable("id") String id){
        return new Result(ResultCode.SUCCESS,departmentService.findDepartmentById(id));
    }

    /**
     * 根据id删除部门
     */
    @DeleteMapping("/department/{id}")
    public Result deleteDepartmentById(@PathVariable("id") String id){
         Integer rows=departmentService.deleteDepartmentById(id);
         if(rows<1){
             return new Result(ResultCode.FAIL);
         }
         return new Result(ResultCode.SUCCESS);
    }


    /**
     * 修改部门
     */
    @PutMapping("/department/{id}")
    public Result updateDepartment(@PathVariable("id") String id, @RequestBody Department department){
        department.setId(id);
        department.setCompanyId(this.companyId);
        Integer rows=departmentService.updateDepartment(department);
        if(rows<1){
            return new Result(ResultCode.FAIL);
        }
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 新增部门
     */
    @PostMapping("/department")
    public Result addDepartment(@RequestBody Department department){
        department.setId(String.valueOf(idWorker.nextId()));
        department.setCompanyId(this.companyId);
        department.setCreateTime(new Date());
        Integer rows=departmentService.addDepartment(department);
        if(rows<1){
            return new Result(ResultCode.FAIL);
        }
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 根据部门编码以及企业id查询部门信息
     */
    @RequestMapping(value="/department/search",method = RequestMethod.POST)
    public Department findByCode(@RequestParam(value="code") String code,@RequestParam(value="companyId") String companyId) {
        Department dept = departmentService.findByCode(code,companyId);
        return dept;
    }

}
